package cn.netjava.robo3d;

import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

import cn.netjava.robo3d.test.Test;

import com.jme.app.BaseSimpleGame;
import com.jme.bounding.BoundingBox;
import com.jme.image.Image;
import com.jme.image.Texture;
import com.jme.input.AbsoluteMouse;
import com.jme.input.KeyBindingManager;
import com.jme.input.KeyInput;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.Spatial;
import com.jme.scene.state.CullState;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.ZBufferState;
import com.jme.system.DisplaySystem;
import com.jme.system.JmeException;
import com.jme.util.TextureManager;
import com.jme.util.Timer;
import com.jmex.terrain.TerrainBlock;
import com.jmex.terrain.util.MidPointHeightMap;

/**
 * <code>Tutorial 4</code> Builds the environment (surrounding structure and
 * sky). framework for Flag Rush. For Flag Rush Tutorial Series.
 *
 * @author Mark Powell
 */
public class Game extends BaseSimpleGame {
	private static final Logger logger = Logger.getLogger(Game.class.getName());
	// the terrain we will drive over.
	private TerrainBlock tb;
	private float tbroll=0.0f;//地形起伏程度
	// Sky box (we update it each frame)
	private RoboTank car; // 主角 到node就行了

	// private ChaseCamera chaser;
	protected Input input;
	// the timer
	protected Timer timer;
	// Our camera object for viewing the scene
	private Camera cam;

	// the root node of the scene graph
	private Scene scene;
	// display attributes for the window. We will keep these values
	// to allow the user to change them
	private int width, height, depth, freq;
	private boolean fullscreen;

	private DashBoard dash; // 主玩家仪表盘

	/**
	 * Main entry point of the application
	 */
	public static void main(String[] args) {
		Game app = new Game();
		// We will load our own "fantastic" Flag Rush logo. Yes, I'm an artist.
		app.setConfigShowMode(ConfigShowMode.AlwaysShow, Game.class
				.getClassLoader().getResource(
						"cn/netjava/robo3d/images/001.jpg"));
		app.start();
	}

	/**
	 * build the height map and terrain block.
	 */
	private void buildTerrain() {

		MidPointHeightMap heightMap = new MidPointHeightMap(64, 3f);
		// Scale the data
		Vector3f terrainScale = new Vector3f(4, tbroll, 4);
		// create a terrainblock
		tb = new TerrainBlock("tb", heightMap.getSize(), terrainScale,
				heightMap.getHeightMap(), new Vector3f(0, 0, 0));
		tb.setModelBound(new BoundingBox());
		tb.updateModelBound();
		// This will be the texture for the terrain.
		URL picurl = Game.class.getClassLoader().getResource(
				"cn/netjava/robo3d/images/terrain.jpg");
		TextureState ts = display.getRenderer().createTextureState();
		ts.setTexture(TextureManager.loadTexture(picurl,
				Texture.MinificationFilter.BilinearNearestMipMap,
				Texture.MagnificationFilter.Bilinear));
		tb.setRenderState(ts);
		// tb.setRenderQueueMode(Renderer.QUEUE_OPAQUE);
		scene.attachChild(tb);
	}

	/**
	 * clean up the textures.
	 *
	 * @see com.jme.app.BaseGame#cleanup()
	 */
	protected void cleanup() {

	}

	/**
	 * initializes the scene
	 *
	 * @see com.jme.app.BaseGame#initGame()
	 */
	protected void initGame() {
		input = new Input();                               			//初始化输入设备
		scene = new Scene(input, cam);   		//初始化场景

		/**
		 * Create a ZBuffer to display pixels closest to the camera above
		 * farther ones.
		 */
		ZBufferState buf = display.getRenderer().createZBufferState();
		buf.setEnabled(true);
		buf.setFunction(ZBufferState.TestFunction.LessThanOrEqualTo);
		scene.setRenderState(buf);

		// Time for a little optimization. We don't need to render back face
		// triangles, so lets
		// not. This will give us a performance boost for very little effort.
		CullState cs = display.getRenderer().createCullState();
		cs.setCullFace(CullState.Face.Back);
		scene.setRenderState(cs);
		// Add terrain to the scene
		buildTerrain();                                                  //初始化,载入地形

		car = scene.getCar(); 										  // 得到主角
		dash = new DashBoard(car);							  //初始化面板
		scene.attachChild(dash);									  //载入面板

		// update the scene graph for rendering 系统设置
		scene.updateGeometricState(0.0f, true);
		scene.updateRenderState();
	}

	/**
	 * initializes the display and camera.
	 * 初始化系统
	 * @see com.jme.app.BaseGame#initSystem()
	 */
	protected void initSystem() {
		// store the properties information
		width = settings.getWidth();
		height = settings.getHeight();
		depth = settings.getDepth();
		freq = settings.getFrequency();
		fullscreen = settings.isFullscreen();

		try {

			display = DisplaySystem.getDisplaySystem(settings.getRenderer());
			display.createWindow(width, height, depth, freq, fullscreen);

			cam = display.getRenderer().createCamera(width, height);
		} catch (JmeException e) {
			logger.log(Level.SEVERE, "Could not create displaySystem", e);
			System.exit(1);
		}
		display.setTitle("坦克-www.NetJava.cn");
		// set the background to black
		display.getRenderer().setBackgroundColor(ColorRGBA.black.clone());

		// initialize the camera
		cam.setFrustumPerspective(45.0f, (float) width / (float) height, 0.1f,
				5000);
		/** Signal that we've changed our camera's location/frustum. */
		cam.update();
		/** Get a high resolution timer for FPS updates. */
		timer = Timer.getTimer();
		display.getRenderer().setCamera(cam);
		KeyBindingManager.getKeyBindingManager().set("exit",
				KeyInput.KEY_ESCAPE);

	}

	/**
	 * close the window and also exit the program.
	 */
	protected void quit() {
		super.quit();
		System.exit(0);
	}

	/**
	 * will be called if the resolution changes
	 *
	 * @see com.jme.app.BaseGame#reinit()
	 */
	protected void reinit() {
		display.recreateWindow(width, height, depth, freq, fullscreen);
	}

	/**
	 * draws the scene graph
	 *
	 * @see com.jme.app.SimpleGame#render
	 */
	protected void render(float interpolation) {
		// Clear the screen
		display.getRenderer().clearBuffers();
		display.getRenderer().draw(scene);
	}

	/**
	 * During an update we look for the escape button and update the timer to
	 * get the framerate. Things are now starting to happen, so we will update
	 *
	 * @see com.jme.app.SimpleGame#update
	 */
	protected void update(float interpolation) {
		// update the time to get the framerate
		timer.update();
		interpolation = timer.getTimePerFrame();
		// 更新场景
		scene.updatescene(interpolation);

		// if escape was pressed, we exit
		if (KeyBindingManager.getKeyBindingManager().isValidCommand("exit")) {
			finished = true;
		}
		// 给主角加上键盘
		if (KeyBindingManager.getKeyBindingManager().isValidCommand("forward",
				true)) {
			car.setdirection(RoboTank.forwardflag);
			car.controloilrate();
		}
		if (KeyBindingManager.getKeyBindingManager().isValidCommand("backward",
				true)) {
			car.setdirection(RoboTank.backwardflag);
			car.controloilrate();
		}
		if (KeyBindingManager.getKeyBindingManager().isValidCommand(
				"turnRight", true)) {
			car.turnright();
		}
		if (KeyBindingManager.getKeyBindingManager().isValidCommand("turnLeft",
				true)) {
			car.turnleft();
		}
		if (KeyBindingManager.getKeyBindingManager().isValidCommand(
				"changeGear", false)) {
			car.changeGear();
		}
		if (KeyBindingManager.getKeyBindingManager().isValidCommand("firegun",
				true)) {
			car.firegun();
		} else {
			car.endfiregun();
		}
		if (KeyBindingManager.getKeyBindingManager().isValidCommand("caseleft",
				true)) {
			car.leftcasemate(1.5f);
		}
		if (KeyBindingManager.getKeyBindingManager().isValidCommand(
				"caseright", true)) {
			car.rightcasemate(1.5f);
		}
		if (KeyBindingManager.getKeyBindingManager().isValidCommand("shoot",
				false)) {
			car.shoot();
		}
		if(KeyBindingManager.getKeyBindingManager().isValidCommand("jump",
				false)){
			car.jump();
		}

		// 刷新仪表盘
		dash.updatetext(); // 只给主玩家,由于是面对对象,引用的是同一个car.

		// Because we are changing the scene (moving the skybox and player) we
		// need to update
		// the graph.
		scene.updateGeometricState(interpolation, true);

	}

	@Override
	protected void simpleInitGame() {
		// TODO Auto-generated method stub

	}


}
